/*
 * @Author: herw
 * @Date: 2020-11-13 14:31:53
 * @Last Modified by: herw
 * @Last Modified time: 2020-12-02 19:19:45
 */
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.name"
          clearable
          placeholder="输入应用名称查询"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <template slot="left">
          <el-button
            v-permission="['admin', 'definition:edit']"
            :disabled="!selectIndex"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-upload"
            @click="crud.toEdit(currentRow)"
          >查看
          </el-button>
          <el-button
            v-permission="['admin', 'definition:edit']"
            :disabled="!selectIndex"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-upload"
            @click="image"
          >流程图
          </el-button>
          <el-button
            v-permission="['admin', 'definition:add']"
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-upload"
            @click="importXML"
          >导入
          </el-button>
        </template>
      </crudOperation>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      highlight-current-row
      style="width: 100%"
      @selection-change="handleCurrentChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="key" label="流程定义KEY" />
      <el-table-column prop="name" label="流程定义名称" />
      <el-table-column prop="category" label="流程定义分类" />
      <el-table-column prop="version" label="版本" />
      <el-table-column prop="suspended" label="状态">
        <template slot-scope="scope">
          <span>{{ scope.row.suspended ? '挂起' : '激活' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="formKey" label="表单KEY" />
      <el-table-column
        v-permission="['admin', 'definition:edit', 'definition:del']"
        label="操作"
        align="center"
        width="250"
      >
        <template slot-scope="scope">
          <el-popover
            :ref="'definition' + scope.row.id"
            v-permission="['admin', 'definition:del']"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs['definition' + scope.row.id].doClose()"
              >取消</el-button>
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="delMethod(scope.row.id)"
              >确定</el-button>
            </div>
            <el-button slot="reference" type="text" size="mini">删除</el-button>
          </el-popover>
          <el-popover
            :ref="'instance' + scope.row.id"
            v-permission="['admin', 'definition:del']"
            placement="top"
            width="180"
          >
            <p>确定删除本条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs['instance' + scope.row.id].doClose()"
              >取消</el-button>
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="delMethod(scope.row.id, true)"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              type="text"
              size="mini"
            >删除实例</el-button>
          </el-popover>
          <el-button
            v-permission="['admin', 'definition:edit']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="updateStatus(scope.row, scope.row.suspended)"
          >
            {{ scope.row.suspended ? '激活' : '挂起' }}
          </el-button>
          <el-button
            v-permission="['admin', 'definition:edit']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="identityLink(scope.row)"
          >授权
          </el-button>
          <el-button
            v-permission="['admin', 'definition:list']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="exportXML(scope.row)"
          >导出
          </el-button>
          <el-button
            v-permission="['admin', 'instance:list']"
            style="margin-left: 3px"
            type="text"
            size="mini"
            @click="instance(scope.row)"
          >实例列表
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="800px"
    >
      <el-form
        ref="form"
        :model="form"
        size="small"
        label-width="100px"
        disabled
      >
        <el-form-item label="流程定义KEY" prop="key">
          <el-input
            v-model="form.key"
            style="width: 670px"
            placeholder="流程定义KEY"
          />
        </el-form-item>
        <el-form-item label="流程定义名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 670px"
            placeholder="流程定义名称"
          />
        </el-form-item>
        <el-form-item label="流程定义分类" prop="category">
          <el-input
            v-model="form.category"
            style="width: 670px"
            placeholder="流程定义分类"
          />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input
            v-model="form.version"
            style="width: 670px"
            placeholder="版本"
          />
        </el-form-item>
        <el-form-item label="状态" prop="suspended">
          <el-input
            v-model="form.suspended ? '挂起' : '激活'"
            style="width: 670px"
            placeholder="状态"
          />
        </el-form-item>
        <el-form-item label="表单KEY" prop="formKey">
          <el-input
            v-model="form.formKey"
            style="width: 670px"
            placeholder="表单KEY"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="crud.cancelCU">关闭</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="流程定义导入" :visible.sync="dialogImportVisible">
      <el-upload
        class="upload-demo"
        drag
        action
        :show-file-list="false"
        :before-upload="beforeUpload"
        :http-request="doImport"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">只能上传.bpmn20.xml,.bpmn,.bar,.zip文件，且不超过512K</div>
      </el-upload>
    </el-dialog> -->
    <!--流程图组件-->
    <process-image
      ref="processImage"
      :key="times"
      :process-definition-id="processDefinitionId"
    />
    <!--授权组件-->
    <identity-link
      v-if="dialog"
      :visible.sync="dialog"
      :process-definition-id="processDefinitionId"
      :process-definition-name="processDefinitionName"
    />
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import crudDefinition from '@/api/flowable/definition'
import processImage from '../components/ProcessImage'
import identityLink from './identityLink'
import { downloadFile } from '@/utils'

const defaultForm = {}
export default {
  name: 'ProcessDefinition',
  components: { identityLink, processImage, pagination, crudOperation, rrOperation },
  cruds() {
    return CRUD({ title: '流程定义', url: 'api/flowable/definition', crudMethod: { ...crudDefinition }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      delLoading: false,
      dialog: false,
      currentRow: null,
      selectIndex: '',
      processDefinitionId: '',
      processDefinitionName: '',
      times: 0,
      permission: {
        add: ['admin', 'definition:add'],
        edit: ['admin', 'definition:edit'],
        del: ['admin', 'definition:del']
      }
    }
  },
  created() {
    this.crud.optShow = {
      add: false,
      edit: false,
      del: false,
      download: false
    }
  },
  methods: {
    // 导入
    importXML() {
      // this.dialogImportVisible = true
    },
    // beforeUpload(file) {
    //   // 上传前格式与大小校验
    //   const fileName = file.name
    //   const isFileTypeOk = fileName.endsWith('.bpmn20.xml') || fileName.endsWith('.bpmn') || fileName.endsWith('.bar') || fileName.endsWith('.zip')
    //   const isLt512 = file.size / 1024 / 512 < 1
    //   if (!isFileTypeOk) {
    //     this.crud.notify('上传文件格式不正确', CRUD.NOTIFICATION_TYPE.ERROR)
    //   }
    //   if (!isLt512) {
    //     this.crud.notify('上上传文件大小不能超过512K', CRUD.NOTIFICATION_TYPE.ERROR)
    //   }
    //   return isFileTypeOk && isLt512
    // },
    // doImport(fileObj) {
    //   const formData = new FormData()
    //   formData.set('file', fileObj.file)
    //   // formData.set("tenantId", this.importTenantId);
    //   postAction('/flowable/processDefinition/import', formData).then(({ msg }) => {
    //     this.dialogImportVisible = false
    //     this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
    //     this.crud.toQuery()
    //   })
    // },
    // 导出XML
    exportXML(row) {
      crudDefinition.exportXML(row.id).then(res => {
        downloadFile(res, row.name + '-v' + row.version + '.bpmn20', 'xml')
      }).catch(err => {
        console.log(err.response.data.message)
      })
    },
    // 授权
    identityLink(row) {
      this.processDefinitionId = row.id
      this.processDefinitionName = row.name
      this.dialog = true
    },
    // 查看流程图
    image() {
      this.$refs.processImage.dialog = true
    },
    // 改变状态
    updateStatus(row, status) {
      if (status) {
        crudDefinition.activate(row).then(res => {
          this.crud.toQuery()
          this.crud.notify('激活成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(err => {
          console.log(err.response.data.message)
        })
      } else {
        crudDefinition.suspend(row).then(res => {
          this.crud.toQuery()
          this.crud.notify('挂起成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(err => {
          console.log(err.response.data.message)
        })
      }
    },
    // 实例
    instance(row) {
      this.$router.push({ path: '/workflow/flowable/instance', query: { processDefinitionId: row.id }})
    },
    delMethod(id, cascade) {
      this.delLoading = true
      crudDefinition.del(id, cascade).then(() => {
        this.delLoading = false
        this.$refs[(cascade === undefined ? 'definition' : 'instance') + id].doClose()
        this.crud.dleChangePage(1)
        this.crud.delSuccessNotify()
        this.crud.toQuery()
      }).catch(() => {
        this.delLoading = false
        this.$refs[(cascade === undefined ? 'definition' : 'instance') + id].doClose()
      })
    },
    handleCurrentChange(selection) {
      this.crud.selections = selection
      if (selection.length === 1) {
        const row = selection[0]
        this.selectIndex = row.id
        this.currentRow = row
        this.times = this.times + 1
        this.processDefinitionId = row.id
        this.processDefinitionName = row.name
      } else {
        this.currentRow = {}
        this.selectIndex = ''
      }
    }
  }
}
</script>

<style scoped>
</style>
